//
//  HYFEmoticonToolBar.swift
//  MyWeibo
//
//  Created by 黄勇锋 on 16/7/29.
//  Copyright © 2016年 黄勇锋. All rights reserved.
//

import UIKit

// 给 button.tag 赋值的时候,要加上 tagNum .因为枚举值 .Default .Emoji .Lxh 已经被 View 占用了.
private let tagNum = 2000

enum HYFEmoticonToolBarType:Int{
    
    case Default = 0
    case Emoji = 1
    case Lxh  = 2
}


class HYFEmoticonToolBar: UIStackView {
    
    //定义一个闭包,
    var closure:((type:HYFEmoticonToolBarType)->())?
    //定义一个选中的 button
    var selectedButton:UIButton?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        //添加控件
        addChildButton("left", title: "默认",type: .Default)
        addChildButton("mid", title: "Emoji",type: .Emoji)
        addChildButton("right", title: "浪小花",type: .Lxh)
        //设置排列方向
        axis = .Horizontal
        //填充方式
        distribution = .FillEqually
    }
    
    //抽取一个方法,封装代码
    func setupCurrentButtons(button:UIButton){
        
        if button == selectedButton{
            return
        }
 
        // 取消之前的 选中状态
        selectedButton?.selected = false
        //把当前被点击的 button 座位选中的 button
        selectedButton = button
        //把点击的 button 设为选中状态
        button.selected = true
    }
    
    //提供一个方法,供外界调用
    func setupCurrentButton(tag:Int){
        
        let button = viewWithTag(tag + tagNum) as! UIButton
        
        setupCurrentButtons(button)
    }
    
    //监听方法
    func buttonClick(button:UIButton){
        
        setupCurrentButtons(button)
        //执行闭包
        closure?(type:HYFEmoticonToolBarType(rawValue: button.tag - tagNum)!)
    }
    
    func addChildButton(imgName:String,title:String,type:HYFEmoticonToolBarType) {
        
        let button = UIButton()
        //默认情况下,默认按钮被选中
        if type == .Default{
            
            button.selected = true
            selectedButton = button
        }
        
//        setupCurrentButtons(button)
        
        button.setTitle(title, forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.darkGrayColor(), forState: .Selected)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imgName)_normal"), forState: .Normal)
        button.setBackgroundImage(UIImage(named:"compose_emotion_table_\(imgName)_selected" ), forState: .Selected)
        
        button.tag = type.rawValue + tagNum
        //添加点击事件
        button.addTarget(self, action: #selector(HYFEmoticonToolBar.buttonClick(_:)), forControlEvents: .TouchUpInside)
        //添加子控件
        addArrangedSubview(button)
    }
}
